package com.fyzs.mp3recorder

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.os.Handler
import android.os.HandlerThread
import android.util.AttributeSet
import android.util.Log
import android.view.View
import java.io.DataInputStream
import java.io.File
import java.io.FileInputStream
import kotlin.math.abs
import kotlin.math.max

/**
 * PCM 波形展示图
 * */
class PcmWaveView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {


    private var xSpan=0f
    private var ySpan=1f
    private var lastYSpan = 1f

    val TAG = "PcmWaveView"
    val handlerThread = HandlerThread("aa").apply { start() }
    val workHandler = Handler(handlerThread.looper)


    var maxValue = 0
    fun setPcmFile(file:File){
        Log.i(TAG, "setPcmFile: ")
        if (!file.exists()) {
            return
        }
        
            Log.i(TAG, "setPcmFile: runnable")

            val dataInputStream = DataInputStream(FileInputStream(file))
            val list = ArrayList<Short>()
            
            while (dataInputStream.available()>0){
                val s = dataInputStream.readShort()
                list.add(s)
                if(maxValue < abs(s.toInt())){
                    maxValue = abs(s.toInt())
                }
            }
            dataInputStream.close()
            setPcmData(list)

    }

    private var mPcmDataList = ArrayList<Short>()

    private val mPaint = Paint().apply {
        color = Color.YELLOW
        style = Paint.Style.FILL

    }
    fun setPcmData(pcm:ShortArray){
        setPcmData(pcm.toList())
    }
    fun setPcmData(pcm:List<Short>){
        mPcmDataList.clear()
        mPcmDataList.addAll(pcm)
        Log.i(TAG, "setPcmData: ${mPcmDataList.size}")
        for (i in mPcmDataList) {
            if(maxValue<i)maxValue = i.toInt()
        }
        post {
            requestLayout()
            postInvalidate()
        }
    }
    fun setScale(s:Float){
        ySpan=s
        requestLayout()
        postInvalidate()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        if (mPcmDataList.size==0) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        }else{
            val makeMeasureSpec =
                MeasureSpec.makeMeasureSpec(mPcmDataList.size*max(ySpan.toInt(),1), MeasureSpec.EXACTLY)
            super.onMeasure(makeMeasureSpec, heightMeasureSpec)
        }
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)

        canvas?.drawColor(Color.BLACK)
        mPaint.setColor(Color.WHITE)

        canvas?.drawLine(0f,measuredHeight/2f,measuredWidth.toFloat(),measuredHeight/2f,mPaint)
        if (mPcmDataList.isEmpty()) {
            Log.i(TAG, "onDraw: empty")
            return
        }

        var t = (measuredWidth.toFloat()/mPcmDataList.size)

        mPaint.setColor(Color.YELLOW)

        val f = max(ySpan,1f)*(measuredHeight.div(maxValue.toFloat()))/3
        val offset = measuredHeight/2f
        var x = t*max(ySpan,1f)
        var y = offset
        for (sh in mPcmDataList) {
            val ny = sh.toInt()*f + offset
            val nx =x+1
            canvas?.drawLine(x,y,nx,ny,mPaint)

            x = nx
            y = ny
        }
    }
}